<?php

namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Articles;
use App\ArticleCates;

class ArticleController extends Controller
{
	
	public $pageSize = null;
	
	
	public function __construct()
	{
		$this->pageSize	 = CS('front_page_size')!=''?CS('front_page_size'):20;
	}
	
	
	
	/**
	 * 文章列表
	 */
    public function index(Request $req,$id)
    {			
		//判断是分类否存在
		if(ArticleCates::where('cat_id',$id)->count() < 1)
		{
			return redirect('/');
		}
		
		//查询出该栏目以及子级栏目的文章
		$child = [$id];
		$child = array_merge($child,(new ArticleCates)->getChild($id));
		
		$data =   Articles::orderBy('sort_order','asc')
				->where('is_show',0)
				->whereIn('cat_id',$child)
            	->paginate($this -> pageSize);	
		$cate 	= $this->getCateInfo($id);	
		$title 	= $cate->cat_name.'-'.CS('site_name');
		return view('home.article.article_list',[
			'title'		=> 	$title,
			'hots'		=>  $this->getHots($id),
			'navs'		=> 	getNav(),
			'helps'		=> 	getArt(4),
			'data'		=>	$data,
			'cate'		=> 	$cate,
		]);
				
    }
	
	
	/**
	 * 文章详情
	 */
	public	function detail($id)
	{
		//判断是文章否存在
		if(Articles::where('is_show',0)->where('art_id',$id)->count() < 1)
		{
			return redirect('/');
		}

		$detail = Articles::where('art_id',$id)->first();
		
		//增加点击
		Articles::where('art_id',$id)
		->update([
			'click' => $detail->click + 1,
		]);
		
		$cate 	= $this->getCateInfo($detail->cat_id);
		$title 	= $cate->cat_name.'-'.$detail->title.'-'.CS('site_name');
		return view('home.article.detial',[
			'title' 	=>  $title,
			'hots'		=>  $this->getHots($detail->cat_id),
			'detail'	=>	$detail,  
			'navs'		=> 	getNav(),
			'helps'		=> 	getArt(4),
			'cate'		=>  $cate,
		]);
	}


	/**
	 * 查询栏目信息
	 */
	public function  getCateInfo($id)
	{
		return ArticleCates::where('cat_id',$id)->first();
	}

 	
	
	/**
	 * 获取热门文章
	 * @param	$id  	栏目id
	 * @param	$len	截取条数
	 * @return	Obj				
	 */
	public function  getHots($id,$len = 5)
	{
		$child = [$id];
		$child = array_merge($child,(new ArticleCates)->getChild($id));	
		$data =   Articles::orderBy('sort_order','asc')
				->where('is_show',0)
				->where('is_hot',0)
				->whereIn('cat_id',$child)
				->skip(0)->take($len)
				->get();
		return $data;		
	}
}
